require 'uri'
require 'net/https'
require 'net/https'

module Auth
	PASSPORT_HOST = ENV['PASSPORT_HOST']

	def auth_login
		if session and username = session['username']
			return User.first(:name => username)

		elsif params and params[:ticket]
			url = URI "https://#{PASSPORT_HOST}/verify.php?t=#{params[:ticket]}"

			http = Net::HTTP.new(url.host, url.port)
			http.use_ssl = true if url.scheme == 'https'
			http.verify_mode = OpenSSL::SSL::VERIFY_NONE

			resp = http.request_get(url.request_uri, {'Referer' => request.url})
			username = resp.body
			user = User.first_or_create({:name => username}, {:user_group_id => UserGroup.first(:name => 'Anonymous').id}) if username and username != ""
			session[:username] = user.name if user
			redirect session[:original_url]

		else
			session[:original_url] = request.url
			redirect "https://#{PASSPORT_HOST}/login.php?forward=#{request.url}"

		end
	end
end
